import { Controller, UseGuards, Post, Body, Req, Get, Res, Headers } from "@nestjs/common";
import { ApiBody, ApiOperation, ApiTags } from "@nestjs/swagger";
import { LoginDto } from "./dto/login.dto";
import { AuthService } from "./auth.service";
import { WeChatLoginDto } from "./dto/weChatLogin.dto";
import { RefreshJwtAuthGuard } from "./jwt-auth.guard";

@ApiTags("验证")
@Controller("auth")
export class AuthController {
	constructor(private readonly authService: AuthService) {}

	@ApiOperation({ summary: "用户登录" })
	@Post("login")
	async login(@Body() user: LoginDto) {
		return await this.authService.login(user.account, user.password);
	}

	@ApiOperation({ summary: "刷新token" })
	@UseGuards(RefreshJwtAuthGuard)
	@Post("refresh")
	async refreshToken(@Req() req) {
		return await this.authService.refreshToken(req.user);
	}

	@ApiOperation({ summary: "微信登录跳转" })
	@Get("WeChatLogin")
	async WeChatLogin(@Headers() header, @Res() res) {
		const APPID = process.env.APPID;
		// const redirectUri = urlencode(
		//   'http://lms.siyuanren.com/web/login_front.html',
		// );
		res.redirect(
			`https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${header.refere}&response_type=code&scope=snsapi_login&state=STATE#WeChat_redirect`
		);
	}

	@ApiOperation({ summary: "微信登录" })
	@ApiBody({ type: WeChatLoginDto, required: true })
	@Post("WeChat")
	async loginWithWeChat(@Body("code") code: string) {
		return this.authService.loginWithWeChat(code);
	}
}
